package licode.unisop.auth.application.utils;

import licode.unisop.auth.application.vo.UserRoleInfo;
import licode.unisop.platform.client.api.SiPlatformQueryService;
import licode.unisop.provider.conf.SiAssetType;
import licode.unisop.provider.info.SiHoldInfo;
import licode.unisop.provider.vo.SiAssetBO;
import licode.unisop.provider.vo.SiAssetHold;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 获取用户角色信息
 *
 * @author licode
 * @version 1.0
 * @date 2018-05-21 11:45
 */
@Component
public class UserUtil {
    @Resource
    private SiPlatformQueryService siPlatformQueryService;

    public UserRoleInfo getUserRoleInfo(String userId, String platformId, String clientId) {
        StringBuilder roleCodes = new StringBuilder();
        StringBuilder roleNames = new StringBuilder();

        // 获取用户角色
        SiAssetHold userAssets = siPlatformQueryService.getUserAssets(SiHoldInfo.builder()
                .holdId(userId)
                .clientId(clientId)
                .holdType(SiAssetType.AT_USER)
                .platformId(platformId)
                .build());

        if (null != userAssets) {
            if (userAssets.hasCodeTrees()) {
                Map<String, String> roles = userAssets.getCodes().get(SiAssetType.AT_ROLE);
                if (null != roles) {
                    int index = 0;
                    for (Map.Entry<String, String> entry : roles.entrySet()) {
                        roleCodes.append(entry.getKey());
                        SiAssetBO asset = userAssets.getIds().get(entry.getValue());
                        roleNames.append(asset.getName());
                        ++index;

                        if (index < roles.size()) {
                            roleCodes.append(",");
                            roleNames.append(",");
                        }
                    }
                }
            }
        }

        return UserRoleInfo.builder()
                .roleCodes(roleCodes.toString())
                .roleNames(roleNames.toString())
                .build();
    }
}
